<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>基于JS对象的栈</title>
    </head>
    <body></body>
    <script>
        class Stack {
            constructor() {
                this.count = 0;
                this.items = {};
            }
            push(element) {
                this.items[this.count] = element;
                this.count++;
            }
            pop() {
                if (this.isEmpty()) {
                    return undefined;
                }
                this.count--;
                const result = this.items[this.count];
                delete this.items[this.count];
                return result;
            }
            isEmpty() {
                return this.count === 0;
            }
            peek() {
                if (this.isEmpty()) {
                    return undefined;
                }
                return this.items[this.count - 1];
            }
            clear() {
                this.count = 0;
                this.items = {};
            }
            size() {
                return this.count;
            }
            // toString 方法，这里我们需要加这个，数组的不用是因为我们可以使用数组对象默认的toString方法
            toString() {
                if (this.isEmpty()) {
                    return "";
                }
                let objString = `${this.items[0]}`;
                for (let i = 1; i < this.count; i++) {
                    objString += `,${this.items[i]}`;
                }
                return objString;
            }
        }

        /**
            保护数据结构内部的元素：
            如果我们执行下边的代码：
        
        */
        const stack = new Stack();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        console.log(stack.peek());
        console.log(stack.isEmpty());
        console.log(stack.size());
        console.log(Object.getOwnPropertyNames(stack));
        console.log(Object.keys(stack));
        console.log(stack.items);
        // stack.items = "";
        Object.defineProperty(stack, "items", {
            configurable: true,
            writable: true,
            value: [],
        });
        console.log(stack.itmes);
        console.log(stack.isEmpty());
        console.log(stack.size());
    </script>
</html>
